//
//  OauthController.swift
//  SwiftWB
//
//  Created by 远成物流 on 2017/6/27.
//
//

import UIKit
import SVProgressHUD
import MJExtension

class OauthController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavigation()
        
        load()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

///Mark - UI
extension OauthController{
    func setupNavigation() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(leftBtnClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(rightBtnClick))
        navigationItem.title = "授权"
    }
    
    func load() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(Appkey)&redirect_uri=\(AppRedirectURI)"
        
        guard let url = NSURL(string: urlStr) else {
            return
        }
        
        let request = NSURLRequest(url: url as URL)
        
        webView.loadRequest(request as URLRequest)
    }
}

///Mark - 按钮点击
extension OauthController{
    @objc func leftBtnClick(){
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    @objc func rightBtnClick(){
        let js = "document.getElementById('userId').value=709407208@qq.com;document.getElementById('passwd').value=hangeng938257"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

///Mark - WebView delegate
extension OauthController : UIWebViewDelegate{
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
        SVProgressHUD.showError(withStatus: error.localizedDescription)
    }
    
    //true:继续加载网页 false:停止访问
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else{
            return true
        }
        
        let urlstr = url.absoluteString
        
        guard urlstr.contains("code=") else {
            return true
        }
        
        let code = urlstr.components(separatedBy: "code=").last!
        
        //获取授权token
        getAccessToken(code: code)
        
        return false
    }
}

///Mark - Net request
extension OauthController{
    func getAccessToken(code:String) {
        
        NetworkHelper.shareInstance.getAccessToken(code: code) { (result:[String : AnyObject]?, error:Error?) in
            if error != nil{
                return
            }
            
            guard let dict = result else{
                return
            }
            
            let account = UserAccount(dict: dict)
            
            //获取userinfo
            self.getUserInfo(account:account)
        }
    }
    
    
    func getUserInfo(account:UserAccount) {
        guard let accessToken = account.access_token else {
            return
        }
        
        guard let uid = account.uid else {
            return
        }
        
        NetworkHelper.shareInstance.getUserInfo(accessToken: accessToken, uid: uid) { (result : [String : AnyObject]?, error : Error?) in
            
            if error != nil {
                return
            }
            
            guard let dict = result else{
                return
            }
            
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            // 将account对象保存
            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccoutViewModel.shareInstance.accountPath)
            
            // 将account保存为单例对象
            UserAccoutViewModel.shareInstance.account = account
            
            self.dismiss(animated: true, completion: {
                UIApplication.shared.keyWindow?.rootViewController = WelcomController()
            })
        }
    }
}
